require('./PageVersionmanpc.styl');
import { Control } from 'react-keeper';
import { getTime } from 'clientConfig/util/queryurlfield';
import { monStorage, Storage } from 'clientConfig/util/StoreData';
// import Mypdfviewer from 'components/mypdfviewer'
const classNames = require('classnames')
const reactMixin = require('react-mixin');
const Actions = require('./actions');
const Store = require('./store');
const File = require('images/svg/file.svg');
const { Group, TextField, SelectField, DatetimeField, Button, Boxs, Toast, SearchBar, Icon, Crumb, Dialog } = SaltUI;
const Search = require('components/search')
const { HBox, Box, VBox } = Boxs;
const Select = require('images/svg/select/select.svg');
const Selected = require('images/svg/select/selected.svg');
const Newfile = require('images/svg/file/new_file.svg');
const Fileicon = require('images/svg/file/file_icon.svg');
const Rename = require('images/svg/file/rename.svg');
const Conform = require('images/svg/file/conform.svg');
const Cancel = require('images/svg/file/cancel.svg');
const DownloadIcon = require('images/svg/file/download.svg');
const DeleteIcon = require('images/svg/file/delete.svg');
const PrintIcon = require('images/svg/file/print.svg');
const WordIcon = require('images/svg/file/word.svg');
const PdfIcon = require('images/svg/file/pdf.svg');
const XlsxIcon = require('images/svg/file/xlsx.svg');
const ImgIcon = require('images/svg/file/img.svg');
const components = {
    word: WordIcon,
    pdf: PdfIcon,
    xlsx: XlsxIcon,
    img: ImgIcon
}
const SpeicialIcon = (props) => {
    const Specific = components[props.type];
    return <Specific className='svg-icon place' />
}
var list_data = {};//存储每一路径的文件数据信息
class Versionmanpc extends React.Component {

    constructor(props) {
        super(props);
        // this.file_count = 0
        this.state = {
            data: [],//列表数据
            all_active: 0,
            select_length: 0,
            proj_name: '',
            rename: false,//重命名文件夹名
            crumbs: [{ text: '公共区', folder_id: Control.state.folder_id, file_count: 0 }],
            isnewfile: false,
            file_count: 0,
            active: [],

        };
        this.searchRange = ["文件名称"];
        this.handClick = this.handClick.bind(this);
        this.handClickDownload = this.handClickDownload.bind(this);
        this.handClickDelete = this.handClickDelete.bind(this);
        this.handlePrint = this.handlePrint.bind(this);
        this.handClickCreate = this.handClickCreate.bind(this);
        this.handClickCancel = this.handClickCancel.bind(this);
        this.handClickContent = this.handClickContent.bind(this);
        this.handClickRename = this.handClickRename.bind(this);
        this.handClickFolder = this.handClickFolder.bind(this);

    }
    //搜索
    onsearch() {
        let keyword = this.refs.input.value;
        console.log(keyword)
        if (keyword) {
            Actions.search({ file_name: keyword, id: Storage.get('user.id'), proj_name: this.state.proj_name })
        } else {
            let proj_name = Control.state.proj_name;
            Actions.fetch({ proj_name, id: Storage.get('user.id') });
        }
    }
    //点击小方块的选择
    handClick(index) {
        if (this.state.isnewfile) return;
        let t = this;
        if (index == -1) {
            //全选
            this.setState((prevState, props) => ({
                all_active: !prevState.all_active
            }), () => {
                let active = [],
                    select_length = 0;
                let all_active = this.state.all_active;
                if (!all_active) this.setState({ active, select_length })
                else {
                    select_length = all_active ? this.state.data.length : 0;
                    for (let index in this.state.data) {
                        active.push(index - 0);
                    }
                    this.setState({ active, select_length });
                }
            });
        } else {
            let active = t.state.active,
                all_active = false,
                values = active.indexOf(index) == -1;
            if (values) {
                var length = ++this.state.select_length;
                active.push(index);
            } else {
                var length = --this.state.select_length;
                active.splice(values, 1)
            }
            if (length == this.state.data.length) all_active = true
            this.setState({ active, select_length: length, all_active });
        }
    }
    //获取当前钩选中项
    deal() {
        let deal_array = [];
        for (let index in this.state.data) {
            if (this.state.active.indexOf(index - 0) != -1)
                deal_array.push({ index, value: this.state.data[index] })
        }
        return deal_array;
    }
    //单行输入框
    handleTextChange(name, newValue) {
        this.setState({
            [name]: newValue
        });
    }
    //点击下载
    handClickDownload() {
        Actions.download(this.deal())
    }
    //点击删除
    handClickDelete() {
        let t = this;
        Dialog.confirm({
            title: '提示',
            locale: 'en_US',
            content: '确定要永久删除吗?',
            onConfirm() {
                let deal_array = t.deal();
                let file_array = [];
                let folder_array = [];
                for (let item of deal_array) {
                    if (!item.value.folder) {
                        file_array.push(item);
                    } else {
                        folder_array.push(item);
                    }
                }
                let enter = false;
                let cb = () => {
                    if (enter) return;
                    for (let i = 0; i < deal_array.length; i++) {
                        t.setState({ active: [], select_length: 0, all_active: 0 }, () => { enter = true });
                    }
                }
                // debugger
                if (file_array.length > 0 && folder_array.length > 0) {
                    Actions.delete(file_array, cb);
                    Actions.deleteFilePath(folder_array);
                } else if (file_array.length > 0) {
                    Actions.delete(file_array, cb);
                } else if (folder_array.length > 0) {
                    Actions.deleteFilePath(folder_array, cb);
                }
            },
            onCancel() {
            },
        });
    }
    //点击上传文件
    upFile(type) {
        let cur_folder_id = this.state.crumbs[this.state.crumbs.length - 1].folder_id;
        if (Control.state.proj_name) {
            var formData = null
            formData = new FormData(this.refs.btnForm);
            Actions.upFiles({ name: Control.state.proj_name, folder_id: cur_folder_id }, formData)
        } else {
            Toast.show({
                type: 'error',
                content: "请先选择项目名称",
            });
        }
    }
    //点击打印
    handlePrint() {
        var iframe = document.createElement('iframe');
        iframe.width = window.innerWidth;
        // iframe.height = window.innerHeight;
        iframe.onload = function () {
            iframe.contentWindow.print();
            iframe.remove();
        }
        iframe.src = '/its/download_file?file_id=' + this.deal()[0].value.url + '&is_view=1';
        Toast.show({
            type: 'success',
            content: "请等待",
        });
        document.body.appendChild(iframe)
    }
    //点击新建文件夹
    handClickCreate() {
        if (this.state.crumbs.length == 1) {
            Toast.show({
                type: 'error',
                content: "该目录下不能创建文件夹",
            });
            return;
        }
        this.setState({ isnewfile: true }, () => {
            let textfield_input = this.refs.textfield.refs.input.getDOMNode();
            textfield_input.focus();
        })
    }
    //点击取消按钮
    handClickCancel() {
        this.setState({ isnewfile: false, rename: false })
    }
    //点击勾选按钮
    handClickConfirm(btn_id) {
        let t = this;
        let parent_folder_id = this.state.crumbs[this.state.crumbs.length - 1].folder_id;
        // debugger
        this.setState({ isnewfile: false, rename: false }, () => {
            if (btn_id == -1) {
                if (!t.state.text) return;
                let data = this.state.data;
                let text = '';
                for (let i = 0; i < this.state.data.length; i++) {
                    if (!this.state.data[i].folder) continue;
                    if (this.state.data[i].fileName.includes(this.state.text)) {
                        text = this.state.data[i].fileName;
                        break;
                    }
                }
                if (text) {
                    let regex = /[^\(\)]*(\((\d)\))/g;
                    if (regex.test(text)) {
                        let num = text.replace(regex, '$2');
                        num++;
                        text = this.state.text + `(${num})`;
                    } else {
                        text = this.state.text + `(1)`;
                    }
                }
                let folder_name = text ? text : this.state.text;
                this.setState({ data, text: '' }, () => {
                    Actions.createFilePath({ parent_folder_id, folder_name });
                });
            } else {
                //修改文件夹名逻辑
                // debugger
                let id = this.deal()[0].index;
                let data = this.state.data;
                // let name = data[id].fileName;//旧文件名 
                data[id].fileName = this.state[`textfield${id}`];
                Actions.rename({ folder_name: data[id].fileName, folder_id: data[id].folder_id });
                this.setState({ data });
            }
        })
    }
    //点击空白处
    handClickContent(e) {
        if (this.state.isnewfile) {
            if (e.target.nodeName == "INPUT" || e.target.nodeName == "circle" || e.target.nodeName == "rect") return;
            this.setState({ isnewfile: false, rename: false, text: '' })
        }
    }
    //文件夹重命名
    handClickRename() {
        let id = this.deal()[0].index;
        let value = this.deal()[0].value;
        this.setState({ rename: true }, () => {
            let textfield_input = this.refs[`textfield${id}`].refs.input.getDOMNode();
            textfield_input.focus();
            this.setState({ [`textfield${id}`]: value.fileName })
        });
    }
    //点击路径ok
    onClick(idx) {
        if (idx == this.state.crumbs.length - 1) return;
        let data_arr = this.deal();
        if (data_arr.length > 0) {
            this.setState({ active: [], select_length: 0 });
        }
        let arr = this.state.crumbs;
        if (this.state.crumbs.length > 1) {
            arr.splice(idx + 1, this.state.crumbs.length - idx - 1);
            this.setState({ crumbs: arr }, () => {
                let cur_folder_id = this.state.crumbs[this.state.crumbs.length - 1].folder_id;
                let file_count = this.state.crumbs[this.state.crumbs.length - 1].file_count;
                this.setState({ data: list_data[cur_folder_id], file_count })
            });
        }
    }
    //点击文件夹ok
    handClickFolder(id) {
        if (!this.state.data[id].folder) return;
        if (this.state.rename) {
            this.setState({ rename: false });
            return;
        }
        this.state.crumbs[this.state.crumbs.length - 1].file_count = this.state.file_count;
        let arr = this.state.crumbs;
        arr.push({ text: this.state.data[id].fileName, folder_id: this.state.data[id].folder_id, file_count: 0 });
        // debugger
        this.setState({ crumbs: arr, active: [], select_length: 0 }, () => {
            let cur_folder_id = this.state.data[id].folder_id;
            let file_count = this.state.crumbs[this.state.crumbs.length - 1].file_count;
            if (list_data.hasOwnProperty(cur_folder_id)) {
                this.setState({ data: list_data[cur_folder_id], file_count })
            } else {
                Actions.fetch({ proj_name: this.state.proj_name, pathname: this.state.data[id].fileName, folder_id: this.state.data[id].folder_id }, this.cb);
            }
        })
    }
    render() {
        let t = this;
        return (
            <div className="versionmanpc" onClick={(e) => { t.handClickContent(e) }}>
                {/* {this.state.file && <Mypdfviewer file={this.state.file} />} */}
                <div className={classNames({ "t-hide": this.state.file })}>
                    {
                        t.state.crumbs.length > 1 && (
                            <HBox vAlign="center" className="head" >

                                <Box flex={1} >
                                    <HBox vAlign="center">
                                        <Box flex={1}>
                                            <form className="btn-form" ref="btnForm">
                                                <input type="file" value="" name="file" onChange={this.upFile.bind(t, 'file')} />
                                            </form>
                                            <div className="btn-upload"><File height="18" width="16" className="file-icon" /><span className="t-ML8">上传文件</span></div></Box>
                                        <Box flex={1}>
                                            <div className="btn-upload new-file" onClick={this.handClickCreate}>
                                                <Newfile height="18" width="16" className="file-icon" />
                                                <span className="t-ML8">新建文件夹</span>
                                            </div>
                                        </Box>
                                    </HBox>
                                </Box>

                                <Box flex={1}>
                                    <span className="inputBox">
                                        <Icon name="search" height='12px' width="12px" fill="#999" className="searchIcon1" />
                                        <input type="text" className="searchInput" ref="input" placeholder="搜索"
                                            onChange={t.onsearch.bind(t)} />
                                    </span>
                                </Box>
                            </HBox>
                        )
                    }
                    <Group.Head className='group-head t-PL19 t-FAL'><div className="t-MT6">{this.state.proj_name}-文件总数:{this.state.file_count}</div></Group.Head>
                    <Group.Head className='group-head t-PL19 t-FAL'>
                        <HBox className="t-MT6">
                            <Box>{t.state.crumbs.length > 1 && <span className="t-MR20 t-crumb-item" onClick={() => { t.onClick(this.state.crumbs.length - 2) }}>&lt;</span>}</Box>
                            <Box>
                                <Crumb onClick={t.onClick.bind(t)} showScroll={false}>
                                    {
                                        t.state.crumbs.map((crumb, key) => {
                                            return <Crumb.Item key={key}>{crumb.text}</Crumb.Item>
                                        })
                                    }
                                </Crumb>
                            </Box>
                        </HBox>
                    </Group.Head>
                    <Group.Head className='group-head t-PL19 '>
                        {!t.state.select_length ?
                            <HBox vAlign="center" className="t-FAL">
                                <Box flex={2}>
                                    {
                                        !!t.state.all_active ?
                                            <Selected width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(-1) }} />
                                            :
                                            <Select width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(-1) }} />
                                    }
                                    <span >名称</span>
                                </Box>
                                <Box flex={3} className="t-ML15">
                                    <HBox>
                                        <Box flex={2}><span className="t-ML20">更新时间</span></Box>
                                        <Box flex={1}> <span className="t-ML25">大小</span></Box>
                                        <Box flex={1} className="t-FAC"><span>上传者</span></Box>
                                        <Box flex={1} className="t-FAC"><span>版本号</span></Box>
                                    </HBox>
                                </Box>
                            </HBox> :
                            <HBox vAlign="center" className="t-FAL">
                                <Box className="active">
                                    {
                                        !!t.state.all_active ?
                                            <Selected width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(-1) }} />
                                            :
                                            <Select width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(-1) }} />
                                    }
                                    <label >已选中了{t.state.select_length}个文件(文件夹)</label>
                                    {t.state.crumbs.length > 1 && (
                                        <span>
                                            {t.state.select_length == 1 && (t.deal()[0] && !t.deal()[0].value.folder) && <span className="t-ML47" onClick={this.handClickDownload}><DownloadIcon width="15" height="17" className="place" /><span className="t-ML8">下载</span></span>}
                                            < span className="t-ML38" onClick={this.handClickDelete}><DeleteIcon width="15" height="18" className="place" /><span className="t-ML7">删除</span></span>
                                            {t.state.select_length == 1 && (t.deal()[0] && t.deal()[0].value.folder) && <span className="t-ML38" onClick={this.handClickRename}><Rename width="15" height="18" className="place" /><span className="t-ML7">重命名</span></span>}
                                            {t.state.select_length == 1 && (t.deal()[0] && t.deal()[0].value.fileName.includes(".pdf")) && <span className="t-ML38" onClick={this.handlePrint}><PrintIcon width="15" height="18" className="place" /><span className="t-ML7">打印</span></span>}
                                        </span>
                                    )}
                                </Box>
                            </HBox>}
                    </Group.Head>
                    <Group.List >
                        {this.state.isnewfile &&
                            <HBox vAlign="center" className="list-item ">
                                <Box flex={1} className="t-FAL">
                                    <HBox vAlign="center">
                                        <Box flex={1}>
                                            <Select width="22" height="20" className="t-MR19 place" />
                                            <Fileicon className="svg-icon place" />
                                        </Box>
                                        <Box flex={3}  >
                                            <HBox vAlign="center">
                                                <Box flex={3}>
                                                    <TextField
                                                        label=""
                                                        value={t.state.text}
                                                        onChange={t.handleTextChange.bind(t, 'text')}
                                                        placeholder="新建文件夹"
                                                        className="text-field-border"
                                                        ref="textfield"
                                                    />
                                                </Box>
                                                <Box onClick={t.handClickConfirm.bind(t, -1)} id="conform">
                                                    <Conform width="16" height="16" fill="#777777" className="t-ML8" />
                                                </Box>
                                                <Box onClick={t.handClickCancel}>
                                                    <Cancel width="16" height="16" fill="#777777" className="t-ML8" />
                                                </Box>
                                            </HBox>
                                        </Box>
                                    </HBox>
                                </Box>
                                <Box flex={1} className="t-ML27">

                                </Box>
                            </HBox>}
                        {this.state.data.map((item, index) => {
                            return (
                                <HBox vAlign="center" className="list-item " key={"number" + index}>
                                    <Box flex={2} className="t-FAL">
                                        <HBox vAlign="center">
                                            <Box flex={1}>
                                                {
                                                    t.state.active.indexOf(index) != -1 ?
                                                        <Selected width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(index) }} />
                                                        :
                                                        <Select width="22" height="20" className="t-MR19 place" onClick={() => { this.handClick(index) }} />
                                                }
                                                {item.folder ? <Fileicon className="svg-icon place" onClick={t.handClickFolder.bind(t, index)} /> : <SpeicialIcon type={item.fileName.includes("pdf") ? "pdf" : (item.fileName.includes("docx") || item.fileName.includes("doc") ? "word" : (item.fileName.includes("xlsx") ? "xlsx" : "img"))} />}
                                            </Box>
                                            <Box flex={3}  >
                                                {item.folder && t.state.active.indexOf(index) != -1 && t.state.rename ? (
                                                    <HBox vAlign="center">
                                                        <Box flex={3}>
                                                            <TextField
                                                                label=""
                                                                value={eval(`t.state.textfield${index}`)}
                                                                onChange={t.handleTextChange.bind(t, `textfield${index}`)}
                                                                placeholder={item.fileName}
                                                                className="text-field-border"
                                                                ref={`textfield${index}`}
                                                            />
                                                        </Box>
                                                        <Box >
                                                            <Conform width="16" height="16" fill="#777777" className="t-ML8" onClick={t.handClickConfirm.bind(t)} />
                                                        </Box>
                                                        <Box onClick={t.handClickCancel}>
                                                            <Cancel width="16" height="16" fill="#777777" className="t-ML8" />
                                                        </Box>
                                                    </HBox>
                                                ) : <span className="t-ML18 ellips" onClick={t.handClickFolder.bind(t, index)}>{item.fileName}</span>}
                                            </Box>
                                        </HBox>
                                    </Box>
                                    <Box flex={3} className="t-ML15">
                                        <HBox>
                                            <Box flex={2}><span>{item.date}</span></Box>
                                            <Box flex={1}> <span >{
                                                (() => {
                                                    let fileSize = parseInt(item.fileSize);
                                                    fileSize = fileSize > 0 ? fileSize : -fileSize;
                                                    return fileSize != fileSize ? '---' : fileSize <= 1024 ? item.fileSize : fileSize <= 1024 * 1024 ? (fileSize / 1024).toFixed(2) + 'M' : (fileSize / 1024 / 1024).toFixed(2) + 'GB';
                                                })()
                                            }</span></Box>
                                            <Box flex={1} className="t-FAC"><span >{item.file_uper_name}</span></Box>
                                            <Box flex={1} className="t-FAC"><span >{item.file_version ? item.file_version : '无'}</span></Box>
                                        </HBox>
                                    </Box>
                                </HBox>);
                        })
                        }
                    </Group.List>
                    {
                        !this.state.isnewfile && this.state.data.length == 0 && <VBox hAlign="center" className="empty">
                            <Box><Fileicon fill="#777777" width="60px" height="60px" /></Box>
                            <Box className="t-MT8">暂无文件</Box>
                        </VBox>
                    }
                </div>
            </div>
        );
    }

    componentWillMount() {
    }

    componentDidMount() {
        let proj_name = Control.state.proj_name;
        let folder_id = Control.state.folder_id;
        let cb = (pathname, folder_id, data) => {
            list_data[folder_id] = data;
            // this.file_count = this.state.file_count;         
        }
        this.cb = cb;
        Actions.fetch({ proj_name, folder_id, pathname: '公共区' }, cb);
    }

    componentWillReceiveProps(nextProps) {
    }

    shouldComponentUpdate(nextProps, nextState) {
        return true;
    }

    componentWillUpdate(nextProps, nextState) {
    }

    componentDidUpdate(prevProps, prevState) {
    }

    componentWillUnmount() {
        list_data = {};
    }
}

reactMixin.onClass(Versionmanpc, Reflux.connect(Store));

module.exports = Versionmanpc;
